package ru.usu.gv.gui.actions;

import ru.usu.gv.core.GraphCanvas;
import ru.usu.gv.core.GraphEngine;
import ru.usu.gv.core.I18nService;
import ru.usu.gv.graph.Graph;
import ru.usu.gv.graph.Vertex;
import ru.usu.gv.styles.StyleFacade;
import ru.usu.gv.uicomponents.UIEdge;
import ru.usu.gv.uicomponents.UIGraph;
import ru.usu.gv.uicomponents.UIUtilities;
import ru.usu.gv.uicomponents.UIVertex;
import ru.usu.gv.utils.RandomUtilities;

/**
 @author Sergey Pupyrev 
 08.01.2007
 */

public class AddGraphAction extends LongAction
{
	private UIGraph _graph;

	public AddGraphAction(UIGraph graph)
	{
		super(I18nService.get("action.add_graph"));
		_graph = graph;
	}

	public AddGraphAction(Graph graph)
	{
		super(I18nService.get("action.add_graph"));
		_graph = createUIGraph(graph);
	}

	@Override
	protected void runAction()
	{
		GraphCanvas.getInstance().clear();
		GraphEngine.getInstance().getPickListener().clearPickList();
		GraphCanvas.getInstance().setCurrentGraph(_graph);
		_graph.draw();
		UIUtilities.fitGraphIntoWindow();
	}

	private UIGraph createUIGraph(Graph graph)
	{
		UIGraph uiGraph = new UIGraph("Generated graph");
		for (int i = 0; i < graph.getSize(); i++)
		{
			UIVertex uiVertex = new UIVertex(RandomUtilities.generateRandomPoint());
			if (StyleFacade.isShowVertexLabel())
				uiVertex.setLabel(String.valueOf(i));
			uiGraph.addVertex(uiVertex);
		}

		for (int i = 0; i < graph.getSize(); i++)
		{
			Vertex v = graph.getVertex(i);
			for (int j = 0; j < v.getEdgesSize(); j++)
			{
				Vertex u = v.getEdge(j);
				UIVertex vv = uiGraph.getVertexes().get(v.getIndex());
				UIVertex vu = uiGraph.getVertexes().get(u.getIndex());
				uiGraph.addEdge(new UIEdge(vv, vu));
			}
		}
		return uiGraph;
	}

}
